#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>
using namespace std;
#define N 4
int cnt = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *handler(void *args)
{
    pthread_detach(pthread_self());
    int name = (long long)args;
    while (true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);//所有线程都进行等待，没有条件；需要进行唤醒；
        cout << "name-" << name << "-cnt=" << cnt++ << endl;
        pthread_mutex_unlock(&mutex);//会造成其他线程饥饿问题；需要通过同步等待；
        // sleep(1);
    }
    return nullptr;
}
int main()
{
    vector<pthread_t> v;
    for (int i = 0; i < N; i++)
    {
        pthread_t tid;
        pthread_create(&tid, nullptr, handler, (void *)i);
        v.push_back(tid);
        sleep(1);
    }
    // for (auto e : v)
    // {
    //     pthread_join(e, nullptr);
    // }
    while(true)
    {
        pthread_cond_signal(&cond);//每一秒钟进行唤醒；
        sleep(1);
    }
    return 0;
}